//
//  AdViewManager.m
//  ebook
//
//  Created by 吴超飞 on 2016/11/10.
//  Copyright © 2016年 Moton. All rights reserved.
//

#import "AdViewManager.h"
#import "SDWebImageDownloader.h"
#import "DrawCircleProgressButton.h"
#import "UIButton+WebCache.h"
#import "WebViewController.h"
#import "MTTabBarController.h"
#import "MTNavigationController.h"
#import "MTHomeViewController.h"
#import "UIView+Extension.h"
#import "YZGTimer.h"

@interface AdViewManager ()<SplashSDKDelegate>{//GADInterstitialDelegate
    
    BOOL hasRemove;//本广告页是否已经移除
    int timeCount;//实际的倒计时时间
    int clock;//服务端指定的显示倒计时时间
    float showTime;
}

//@property (nonatomic, strong) NSTimer *timer;
//@property (nonatomic, strong) dispatch_source_t gcdTimer;
@property (nonatomic, retain) NSMutableArray *timersArray;
@property (nonatomic, strong) UIButton *advBtn;//显示广告的控件
@property (nonatomic, strong) UIButton *jumpBtn;
@property (nonatomic, strong) UIButton *eventBtn;

@property (nonatomic, strong) BaiduMobAdSplash *splash;
@property (nonatomic, assign) BOOL isFromBackground;
//@property (nonatomic, strong) GADInterstitial *interstitial;

//@property (nonatomic, strong) SplashSDK *tanvSplash;

@property (nonatomic, strong) NSMutableArray *alterlist;
@property (nonatomic, assign) BOOL isLoadingAdWithClose;//是否在加载自带关闭按钮的广告(Google、Jusha)

@property (nonatomic, strong) UIViewController *controller;
@property (nonatomic, strong) UIView *view;

@end

@implementation AdViewManager

+(void)showAdOnController:(UIViewController *)controller isFromBackgroud:(BOOL)isfromback{
    
    AdViewManager *manager = [[AdViewManager alloc] initWichSuperController:controller isFromBackgroud:isfromback];
    [manager showAd];
}

-(instancetype)initWichSuperController:(UIViewController *)controller isFromBackgroud:(BOOL)isfromback{
    
    if (self = [super init]) {
        
        _isFromBackground = isfromback;
        _controller = controller;
        
        if (isfromback) {//从后台进入是在加载在Controller里面的，所以直接使用Controller的视图
            
            _view = _controller.view;
            
            if(_view.width>_view.height){//横屏阅读时需切换广告方向
                float w = _view.width;
                _view.width = _view.height;
                _view.height = w;
            }
        }else{
            
            UIView *fullScreenView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
            _view = fullScreenView;
        }
    }
    return self;
}

- (void)showAd {
    
    [self addBgView];
    
    if(!_isFromBackground){
        UIWindow *window = [[[UIApplication sharedApplication] delegate] window];
        UIView *superView = window.rootViewController.view;
        [superView addSubview:self.view];
        [superView bringSubviewToFront:self.view];
    }
    
    [self showAdView];
}

-(void)dealloc{
    
    MTLog(@"广告dealloc");
}

#pragma mark - 广告、视图、数据加载
- (void)addBgView
{
    //广告图片显示位置
    self.view.backgroundColor = [UIColor whiteColor];
    CGRect f = self.view.bounds;
    float logoHeight = MTScreenW*(230.0/1024);
    f.size.height -= logoHeight;
    UIButton *adv = [[UIButton alloc] initWithFrame:f];
    
    [adv addTarget:self action:@selector(selfAdClick:) forControlEvents:UIControlEventTouchUpInside];
    [adv setContentMode:UIViewContentModeScaleAspectFit];
    _advBtn = adv;
    [self.view addSubview:adv];
    
    UIImageView *imgV = [[UIImageView alloc] init];
    imgV.frame = CGRectMake(0, f.size.height, MTScreenW, logoHeight);
    imgV.contentMode = UIViewContentModeScaleAspectFit;
    imgV.image = [UIImage imageNamed:@"launchDefaults_icon"];
    [self.view addSubview:imgV];
}

- (void)showAdView
{
    if([CoreStatus currentNetWorkStatus]==CoreNetWorkStatusNone) {
        [self remove];//没网络移除
    }
    
    if([[NSUserDefaults standardUserDefaults] doubleForKey:kLastEnterBackgroundTime]>0){//第一次启动时不显示广告，但是后台切换到前台时需要显示
        
        NSDictionary *dict = kBookCityDataDict;
        NSArray *alterlist = dict[@"data"][@"ad"][@"splash"][@"alterlist"];
        _alterlist = [NSMutableArray arrayWithArray:alterlist];
        showTime = [dict[@"data"][@"ad"][@"splash"][@"showtime"] floatValue];
        if(showTime==0)showTime = kDefaultShowTime;
        
        NSString *active = dict[@"data"][@"ad"][@"splash"][@"active"];//默认广告类型
        //        active=@"baidu";
        [self loadSplashAd:active];
    }else{
        [self startTimer];
    }
}

//根据类型加载对应的广告
-(void)loadSplashAd:(NSString *)active{
    
    if([active isEqualToString:@"own"]){//显示自己的广告
        
        [self showSelfAd];
        [self showjumpBtn];
    }else if([active isEqualToString:@"baidu"]){//显示百度广告
        
        [[BaiduMobStat defaultStat] logEvent:kBaiduEvent_BaiduLauchAdRequest eventLabel:@"baiduad"];
        [self.splash loadAndDisplayUsingContainerView:self.advBtn];
        [self showjumpBtn];
    }else if([active isEqualToString:@"google"]){
        //        [self createGoogleInterstitialAndLoad];
    }else if([active isEqualToString:@"tanv"]||[active isEqualToString:@"jushaapi"]){
        
        [self loadTanvAd];
    }
    [self startTimer];
}

//广告加载成功
-(void)adLoadSuccess{
    
    _eventBtn.enabled = YES;
}

//广告请求失败
-(void)adLoadFailed{
    
    [self loadNextSplashAd];
}

-(void)setIsLoadingAdWithClose:(BOOL)isLoadingAdWithClose{
    
    _isLoadingAdWithClose = isLoadingAdWithClose;
    _jumpBtn.hidden = isLoadingAdWithClose;
}

#pragma mark - 定时器

-(void)startTimer{
    
    BOOL isFirst = [[NSUserDefaults standardUserDefaults] doubleForKey:kLastEnterBackgroundTime]==0;//第一次启动
    timeCount = isFirst?showTime/2:showTime;
    [self loadGCDTimer];
}

-(NSMutableArray *)timersArray{
    
    if (!_timersArray) {
        _timersArray = [NSMutableArray array];
    }
    return _timersArray;
}

//定时器设置
-(void)loadGCDTimer{
    
    NSString *timerId = [YZGTimer doTask:^{
        
        [self handleTimer];
    } start:1.f interval:1.f repeats:YES async:NO];
    [self.timersArray addObject:timerId];
}

//启用倒计时计时器，如果超时则直接移除广告页
-(void)handleTimer{
    
    MTLog(@"广告倒计时：%d",timeCount);
    if(clock>0)
        [_jumpBtn setTitle:[NSString stringWithFormat:@"跳 过 %ds" ,clock--] forState:UIControlStateNormal];
    
    if (timeCount<0){
        
        if(!_isLoadingAdWithClose) {
            [self remove];
        }
    }
    timeCount--;
}

-(void)deallocTimer{
    
    [NSThread sleepForTimeInterval:0.2];
    [YZGTimer cancelTask:[self.timersArray firstObject]];
    //     [YZGTimer cancelTask];
    MTLog(@"移除广告定时器");//移除定时器后才会触发dealloc方法，不能过早移除，防止对象被销毁，广告的回调事件无法接收，所以要延迟半秒销毁
}

//一种广告失败后，加载另一种备选广告
-(void)loadNextSplashAd{
    
    if(_alterlist.count>0){
        MTLog(@"广告加载失败后，开始另一种备选广告");
        NSString *next = _alterlist.firstObject;
        [self loadSplashAd:next];
        [_alterlist removeObjectAtIndex:0];
    }else{
        [self remove];
    }
}

#pragma mark - 状态获取

+ (UIViewController *)getCurrentVC
{
    UIViewController *result = nil;
    UIWindow * window = [[[UIApplication sharedApplication] delegate] window];
    if (window.windowLevel != UIWindowLevelNormal){
        
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows){
            
            if (tmpWin.windowLevel == UIWindowLevelNormal){
                
                window = tmpWin;
                break;
            }
        }
    }
    
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;
    
    return result;
}

//当天是否点击过广告
+(BOOL)isClickAdToday{
    
    NSDate *lastDay = [NSDate dateWithTimeIntervalSince1970:[[NSUserDefaults standardUserDefaults] doubleForKey:kLastClickAdTime]];//上次广告点击时间
    return [self dateIsToday:lastDay];
}

//后台切换到前台是否需要显示广告
+(BOOL)isNeedShowAdWhenEnterforground{
    
    //    return YES;
    /*进入后台需要显示广告的情况:
     1.同一天没点击过广告;
     2.显示自售广告，服务端标注的reopen字段为1；
     3.以上条件满足时，进入后台时间超过五分钟,即需要显示广告;
     4.当天点击过，一小时后进入需要显示，同时间广告只需要显示3秒
     */
    NSDictionary *dict = kBookCityDataDict;
    BOOL isSelf=[dict[@"data"][@"ad"][@"splash"][@"active"] isEqualToString:@"own"];
    BOOL isReopen = [dict[@"data"][@"ad"][@"splash"][@"own"][@"reopen"] intValue]==1;
    
    if([AdViewManager isOverTime:5*60]&&![self isClickAdToday]&&(!isSelf||(isSelf&&isReopen)))//当天没点广告的，后台切换过来过5分钟显示
        return YES;
    
    return NO;
}

//进入后台超过指定时间
+(BOOL)isOverTime:(NSTimeInterval)inter{
    
    double interval = [[NSDate date] timeIntervalSince1970]-[[NSUserDefaults standardUserDefaults] doubleForKey:kLastEnterBackgroundTime];
    return interval>inter;
}

//所给的时间是否是今天
+(BOOL)dateIsToday:(NSDate *)date{
    
    NSDate *today = [NSDate date];
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *dateComponents = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:date];
    NSDateComponents *todayComponents = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:today];
    
    return (dateComponents.year==todayComponents.year&&dateComponents.month==todayComponents.month&&dateComponents.day==todayComponents.day);
}

/*跳过按钮是否启用
 *策略：每天第二次点击时失效，其他时候都正常
 */
-(BOOL)isEnableJumpBtn{
    
    NSDate *lastJump = [NSDate dateWithTimeIntervalSince1970:[[NSUserDefaults standardUserDefaults] doubleForKey:kLastClickLaunchJumpTime]];//上次点击跳过的时间
    NSDate *lastClick = [NSDate dateWithTimeIntervalSince1970:[[NSUserDefaults standardUserDefaults] doubleForKey:kLastClickAdTime]];//上次点击广告的时间
    //当天点击点击过跳过按钮，并且未点击过广告，则跳过按钮失效
    if ([AdViewManager dateIsToday:lastJump]&&![AdViewManager dateIsToday:lastClick]&&[self ramdonEnable]) {
        return NO;
    }
    return YES;
}

//根据设定的比率选择是否禁用跳过按钮
-(BOOL)ramdonEnable{
    
    int x = arc4random() % 100;
    NSDictionary *dict = kBookCityDataDict;
    int rate = [dict[@"jumprate"] intValue];
    
    return x<rate;
}

//记录广告的点击时间
-(void)recordAdClickTime{
    
    [[NSUserDefaults standardUserDefaults] setDouble:[[NSDate date]timeIntervalSince1970] forKey:kLastClickAdTime];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

#pragma mark - 百度广告

-(BaiduMobAdSplash *)splash{
    
    if (!_splash) {
        NSDictionary *dict = kBookCityDataDict;
        NSString *serverAdUnitTag = dict[@"data"][@"ad"][@"splash"][@"baidu"][@"AdUnitTag"];
        
        BaiduMobAdSplash *splash = [[BaiduMobAdSplash alloc] init];
        splash.delegate = self;
        splash.AdUnitTag = serverAdUnitTag.length>0?serverAdUnitTag:kBaiduMobDefaultLaunchAdUnitTag;
        splash.canSplashClick = YES;
        _splash = splash;
    }
    return _splash;
}

- (NSString *)publisherId {
    
    NSDictionary *dict = kBookCityDataDict;
    NSString *serverBaiduadid = dict[@"data"][@"ad"][@"splash"][@"baidu"][@"AppId"];
    
    return serverBaiduadid.length>0?serverBaiduadid:kBaiduMobAdPublisherId;
}

- (void)splashDidClicked:(BaiduMobAdSplash *)splash {
    MTLog(@"百度开屏广告点击");
    [self recordAdClickTime];
    [[BaiduMobStat defaultStat] logEvent:kBaiduEvent_BaiduLauchAdUseClick eventLabel:splash.AdUnitTag];
    _eventBtn.hidden = NO;//点击过广告后跳过事件恢复响应
}

- (void)splashDidDismissLp:(BaiduMobAdSplash *)splash {
    
    MTLog(@"百度开屏广告splashDidDismissLp");
}

- (void)splashDidDismissScreen:(BaiduMobAdSplash *)splash {
    
    MTLog(@"百度开屏广告splashDidDismissScreen");
    [self remove];
}

- (void)splashSuccessPresentScreen:(BaiduMobAdSplash *)splash {
    
    MTLog(@"百度开屏广告splashSuccessPresentScreen");
    [[BaiduMobStat defaultStat] logEvent:kBaiduEvent_BaiduLauchAdSuccessPresent eventLabel:splash.AdUnitTag];
    [self adLoadSuccess];
}

- (void)splashlFailPresentScreen:(BaiduMobAdSplash *)splash withError:(BaiduMobFailReason)reason {
    
    MTLog(@"百度开屏加载失败 withError %d", reason);
    [self adLoadFailed];
    [[BaiduMobStat defaultStat] logEvent:kBaiduEvent_BaiduLauchAdFailPresent eventLabel:splash.AdUnitTag];
}

-(int)clockTime{
    
    NSDictionary *dict = kBookCityDataDict;
    NSString *clocktime = dict[@"data"][@"ad"][@"splash"][@"clock"];
    
    return [clocktime intValue];
}

//加上跳过按钮
-(void)showjumpBtn{
    
    clock = [self clockTime];
    [self.jumpBtn setTitle:clock>0?[NSString stringWithFormat:@"跳 过 %ds" ,clock]:@"跳 过" forState:UIControlStateNormal];
    self.eventBtn.hidden=![self isEnableJumpBtn];
    self.eventBtn.enabled = NO;
    
    [self.view addSubview:self.jumpBtn];
    [self.view addSubview:self.eventBtn];
    [self.view bringSubviewToFront:self.eventBtn];
}

-(UIButton *)jumpBtn{
    
    if (!_jumpBtn) {
        UIButton *jumpBtn = [[UIButton alloc]initWithFrame:CGRectMake(self.view.frame.size.width - 100, 35 + (iPhoneX?44:0), 75, 30)];
        [jumpBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        jumpBtn.titleLabel.font = [UIFont systemFontOfSize:16];
        jumpBtn.backgroundColor = [UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:0.3];
        jumpBtn.layer.cornerRadius = 5.0f;
        _jumpBtn = jumpBtn;
    }
    return _jumpBtn;
}

-(UIButton *)eventBtn{
    
    if (!_eventBtn) {
        float scale = 0.6f;//显示区域与点击区域的比值
        UIButton *eventBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.jumpBtn.frame)/scale, CGRectGetHeight(self.jumpBtn.frame)/scale)];
        self.jumpBtn.enabled = NO;//让底下的倒计时button不要接收时间处理
        [eventBtn addTarget:self action:@selector(jumpClick:) forControlEvents:UIControlEventTouchUpInside];
        eventBtn.center=self.jumpBtn.center;
        _eventBtn = eventBtn;
    }
    return _eventBtn;
}

#pragma mark - 自售广告
-(void)showSelfAd{
    
    NSDictionary *dict = kBookCityDataDict;
    NSString *selfAdurl = dict[@"data"][@"ad"][@"splash"][@"own"][@"img"];
    [_advBtn sd_setBackgroundImageWithURL:[NSURL URLWithString:selfAdurl] forState:UIControlStateNormal completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        [_advBtn setBackgroundImage:image forState:UIControlStateHighlighted];//设置高亮状态，防止按下变灰
        if(image){
            [[BaiduMobStat defaultStat] logEvent:kBaiduEvent_LaunchAd_ShowSelfAdSuccess eventLabel:@"展示成功"];
        }else{
            [self remove];
        }
    }];
}

//自定义的广告点击时间
-(void)selfAdClick:(UIButton *)btn{
    
    MTLog(@"自售广告点击");
    [self recordAdClickTime];
    
    NSDictionary *dict = kBookCityDataDict;
    NSString *urlStr = dict[@"data"][@"ad"][@"splash"][@"own"][@"url"];
    int isopenapp = [dict[@"data"][@"ad"][@"splash"][@"own"][@"isopenapp"] intValue];
    if (isopenapp == 0) {//浏览器中打开
        if(!urlStr||urlStr.length==0){
            return;
        }else if (urlStr.length>0&&![urlStr hasPrefix:@"http"]) {
            urlStr = [NSString stringWithFormat:@"http://%@", urlStr];
        }
        WebViewController *webView = [[WebViewController alloc] init];
        webView.url = urlStr;
        
        MTTabBarController *tab = (MTTabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
        [(MTNavigationController *)tab.selectedViewController pushViewController:webView animated:YES];
    }else if (isopenapp == 1) {//打开应用
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr]];
    }
    
//    [self remove];   //自售广告点击事件暂时屏蔽，防止显示其他广告时，点击底部logo会直接跳过广告
    [[BaiduMobStat defaultStat] logEvent:kBaiduEvent_ADClick eventLabel:urlStr];
}

//点击跳过广告
-(void)jumpClick:(UIButton *)btn{
    
    [[BaiduMobStat defaultStat] logEvent:kBaiduEvent_LaunchAdClickJump eventLabel:@"点中了"];
    [self remove];
    
    //记录用户点击跳过的时间
    [[NSUserDefaults standardUserDefaults] setDouble:[[NSDate date]timeIntervalSince1970] forKey:kLastClickLaunchJumpTime];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

//移除视图及广告
- (void)remove {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [self removeBgView];
        [self removeSplash];
        
        [[NSNotificationCenter defaultCenter]postNotificationName:kAdviewRemoveNotification object:nil];
        
        [self deallocTimer];
    });
}

-(void)removeBgView{
    
    MTLog(@"开始移除广告视图");
    if(_isFromBackground)
        [[UIApplication sharedApplication].keyWindow.rootViewController dismissViewControllerAnimated:NO completion:^{}];
    else
        [self.view removeFromSuperview];
}

// 广告展示结束or展示失败后, 移除splash和delegate
- (void) removeSplash {
    
    if (self.splash) {
        self.splash.delegate = nil;
        self.splash = nil;
        [self.advBtn removeFromSuperview];
    }
}

#pragma mark - 巨鲨Tanv 新版本v2.0.0
-(void)loadTanvAd{
    
    //    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    [[BaiduMobStat defaultStat] logEvent:@"TanvSplashLoad" eventLabel:@"load"];
    SplashSDK *splash = [[SplashSDK alloc]initWithUserId:kTanvUserid appId:kTanvAppid appKey:kTanvAppkey];
    splash.delegate = self;
    [splash loadSplash];
    MTLog(@"开始加载Tanv开屏广告");
    //    });
}

-(void)closeSplash:(SplashSDK *)splashSDK{
    
    [[BaiduMobStat defaultStat] logEvent:@"TanvSplashClose" eventLabel:@"close"];
    [self remove];
    MTLog(@"关闭Tanv开屏广告");
}

-(void)clickSplash:(SplashSDK *)splashSDK{
    
    [self remove];
    [[BaiduMobStat defaultStat] logEvent:@"TanvSplashClick" eventLabel:@"click"];
    MTLog(@"点击并移除Tanv开屏广告");
}

-(void)successToFetchSplash:(SplashSDK *)splashSDK drawFrame:(CGRect)dFrame{
    
    MTLog(@"Tanv开屏广告获取成功");
    self.isLoadingAdWithClose = YES;
    [splashSDK showSplashWithController:_controller];
    //  [splashSDK showSplashWithWindow:[UIApplication sharedApplication].keyWindow];
    [[BaiduMobStat defaultStat] logEvent:@"TanvSplashSuccess" eventLabel:@"success"];
}

-(void)failToFetchSplash:(SplashSDK *)splashSDK error:(NSError *)error{
    
    MTLog(@"Tanv开屏加载失败：%@",error);
    [[BaiduMobStat defaultStat] logEvent:@"TanvSplashFail" eventLabel:@"fail"];
    [self adLoadFailed];
}

/*
 #pragma mark - google全屏插屏
 - (void)createGoogleInterstitialAndLoad {
 
 self.interstitial =
 [[GADInterstitial alloc] initWithAdUnitID:kGoolgeAdMobLaunchInterstitialUnit];
 self.interstitial.delegate = self;
 GADRequest *request = [GADRequest request];
 request.testDevices = @[@"6e3e46e4be1a13f322585c7b9ac2dbda",@"6e40b39f9159f6d3ac5b20c75aa3331a" ];
 [self.interstitial loadRequest:request];
 }
 
 - (void)interstitialDidReceiveAd:(GADInterstitial *)ad{
 
 [self adLoadSuccess];
 [[BaiduMobStat defaultStat] logEvent:@"GoogleLaunchDidReceiveAd" eventLabel:@""];
 if (self.interstitial.isReady) {
 [self.interstitial presentFromRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
 self.isLoadingAdWithClose = YES;
 }
 }
 
 - (void)interstitial:(GADInterstitial *)ad didFailToReceiveAdWithError:(GADRequestError *)error{
 
 MTLog(@"Google开屏加载失败 Error:%@",error);
 [[BaiduMobStat defaultStat] logEvent:@"GoogleLaunchFailToReceiveAd" eventLabel:error.description];
 
 [self adLoadFailed];
 }
 
 - (void)interstitialWillPresentScreen:(GADInterstitial *)ad{
 
 [[BaiduMobStat defaultStat] logEvent:@"GoogleLaunchAdPresentScreen" eventLabel:@""];
 }
 
 - (void)interstitialDidFailToPresentScreen:(GADInterstitial *)ad{
 
 MTLog(@"interstitialDidFailToPresentScreen");
 [self remove];
 [[BaiduMobStat defaultStat] logEvent:@"GoogleLaunchAdFailToPresent" eventLabel:@""];
 }
 
 - (void)interstitialWillDismissScreen:(GADInterstitial *)ad{
 
 [self remove];
 [[BaiduMobStat defaultStat] logEvent:@"GoogleLaunchAdDismiss" eventLabel:@""];
 }
 
 - (void)interstitialWillLeaveApplication:(GADInterstitial *)ad{
 
 [[BaiduMobStat defaultStat] logEvent:@"GoogleLaunchAdUserClick" eventLabel:@""];
 [self recordAdClickTime];
 [self remove];
 } */

@end
